package com.chuangke.mds.service;

import java.util.List;
import java.util.Optional;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.chuangke.mds.entity.Knowledge;
import com.chuangke.mds.esrepository.KnowledgeRepository;

@Service
public class KnowledgeEsService {

	@Autowired
	private ElasticsearchOperations operations;
	@Autowired
	private KnowledgeRepository knowledgeRepository;
//	@Autowired
//	private KnowledgeService knowledgeService;

	public void reIndex() {
		IndexOperations indexOperations = operations.indexOps(Knowledge.class);
		indexOperations.delete();
		indexOperations.create();
	}

//	@Async
//	public void reSyncData() {
//		reIndex();
//
//		List<Knowledge> list = knowledgeService.getKnowledgeList();
//		if (!CollectionUtils.isEmpty(list)) {
//			knowledgeRepository.saveAll(list);
//		}
//	}
	
	@Async
	public void reSyncData(List<Knowledge> list) {
		reIndex();

		if (!CollectionUtils.isEmpty(list)) {
			knowledgeRepository.saveAll(list);
		}
	}

	public void insert() {
		Knowledge searchDataDoc = new Knowledge();
		searchDataDoc.setId("");
		searchDataDoc.setName("测试 的商品");
		knowledgeRepository.save(searchDataDoc);
	}

	public void update() {
		Optional<Knowledge> opt = knowledgeRepository.findById("");
		if (opt.isPresent()) {
			Knowledge searchDataDoc = opt.get();
			searchDataDoc.setName("测试 的商品");
			Knowledge save = knowledgeRepository.save(searchDataDoc);
			System.out.println(save.getName());
		}
	}

	public void delete() {
		knowledgeRepository.deleteById("");
	}

	public void operateIndex() {
		// 删除索引
		boolean delete = operations.indexOps(Knowledge.class).delete();
		// 创建索引
		boolean create = operations.indexOps(Knowledge.class).create();
		// 刷新
		operations.indexOps(Knowledge.class).refresh();
		// 判断 索引是否存在
		boolean exists = operations.indexOps(Knowledge.class).exists();
	}

	public void find() {
		// 条件查询
		CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("name").in("test"));
		SearchHits<Knowledge> search = operations.search(criteriaQuery, Knowledge.class);
	}
}
